<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>作用域插槽</title>
</head>

<body>
    <template id="sub-component">
        <div>
            <header>
                <slot name="header" v-bind:stu="stu"></slot>
            </header>
            <section>
                <!-- 不加name属性，等同于name="default" -->
                <slot v-bind:stu="stu"></slot>
            </section>
            <footer>
                <slot name="footer" v-bind:stu="stu"></slot>
            </footer>
        </div>
    </template>

    <main id="app">
        <h2>引入子组件</h2>
        <sub-component v-for="item in ids" :id="item">
            <!-- 可以使用解构的方式，来直接获取数据对象中的属性 -->
            <template v-slot:header="{stu}">
                <h3>名字：{{stu.name}}</h3>
            </template>
            <template #default="{stu}">
                <p>学校：{{stu.school}}</p>
                <p>性别：{{stu.sex}}</p>
            </template>
            <template #footer="{stu}">
                <h3>电话号码</h3>
                <p>{{stu.tel}}</p>
            </template>
        </sub-component>
    </main>
</body>
<script src="../vue.js"></script>
<script>

    const stus = [
        {
            id: 1,
            name: "奉先",
            age: 35,
            sex: "男",
            tel: "13547811112",
            school: "电子科大"
        },
        {
            id: 2,
            name: "陈科地",
            age: 20,
            sex: "男",
            tel: "13547811113",
            school: "电子科大"
        },
        {
            id: 3,
            name: "龙雪",
            age: 20,
            sex: "女",
            tel: "13547811113",
            school: "电子科大"
        },
    ];

    Vue.component("sub-component", {
        template: "#sub-component",
        props: {
            id: {
                type: Number,
                required: true
            }
        },
        watch: {
            id: {
                immediate: true,
                handler(newVal) {
                    let that = this;
                    // 通过id异步加载数据，模拟ajax
                    setTimeout(() => {
                        that.stu = stus.find(v => v.id == newVal);
                        console.log("数据加载完成：",that.stu);
                        console.log("that = ",that);
                    }, 1000)
                }
            }
        },
        data() {
            return {
                stu: {}
            }
        }
    })

    new Vue({
        el: "#app",
        data() {
            return {

                ids: [
                    1, 2, 3
                ]
            }
        }
    })
</script>

</html>